package com.chalk.util;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chalk.common.plugins.fastdfs.FastDFSClient;
import com.chalk.common.util.RestTemplateUtil;
import com.chalk.dto.MiniQrDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoqiang
 * @Description
 * @date 2019/6/11 16:12
 */
@Component
public class WxUtil {
    private Logger log = LoggerFactory.getLogger(WxUtil.class);

    @Value("${wx-mini.appId}")
    private String miniAppId;

    @Value("${wx-mini.appsecret}")
    private String miniAppsecret;

    @Value("${fdfs.server-path}")
    private String serverPath;

    @Autowired
    private RestTemplateUtil<String> restTemplateUtil;

    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 获取小程序码
     * @param miniQrDto
     * @return
     */
    public String getminiQr(@Validated MiniQrDto miniQrDto) {
        RestTemplate rest = new RestTemplate();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + getMiniToken();
        Map<String, Object> param = new HashMap<>();
        param.put("scene", miniQrDto.getScene());
        param.put("page", miniQrDto.getPage());
        param.put("width", 430);
        param.put("auto_color", false);
        Map<String, Object> lineColor = new HashMap<>();
        lineColor.put("r", 0);
        lineColor.put("g", 0);
        lineColor.put("b", 0);
        param.put("line_color", lineColor);
        log.info("调用生成微信URL接口传参:" + param);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        HttpEntity requestEntity = new HttpEntity(param, headers);
        ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
        try {
            JSONObject jsonObject = JSONUtil.parseObj(new String(entity.getBody()));
            // 请求错误时返回Json对象
            if (StringUtils.isNotBlank(jsonObject.get("errcode").toString())) {
                log.info("获取小程序码失败：" + jsonObject);
                return null;
            }
        } catch (JSONException e) {
            log.info("获取小程序码成功");
        }
        InputStream inputStream;
        String imageUrl;
        try {
            inputStream = new ByteArrayInputStream(entity.getBody());
            imageUrl = fastDFSClient.uploadStream(inputStream, entity.getBody().length, "112.png");
            log.info("小程序码地址：" + serverPath + imageUrl);
            return serverPath + imageUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信小程序获取accessToken
     * @return
     */
    private String getMiniToken(){
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+miniAppId+"&secret="+miniAppsecret;
        String resultToken = restTemplateUtil.doGet(tokenUrl).getBody();
        JSONObject jsonObject = JSONUtil.parseObj(resultToken);
        return (String) jsonObject.get("access_token");
    }
}
